package com.knife.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.NewsService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.object.News;
import com.knife.news.object.Type;
import com.knife.util.CommUtil;

public class GenerateTypeTask extends BackGroundTask {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6505431089540836246L;
	private String tid;

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	SiteService siteDAO = SiteServiceImpl.getInstance();
	TypeService typeDAO = TypeServiceImpl.getInstance();
	NewsService newsDAO = NewsServiceImpl.getInstance();
	HTMLGenerater g;
	Type gtype = new Type();
	List<Type> gtypes = new ArrayList<Type>();
	List<News> allNews = new ArrayList<News>();
	Collection<Object> paras;
	String sql;
	int rows;
	int pageSize;
	int totalPage;
	int nowPage;

	public void init() {
		name = "generate type";
		try {
			gtype = typeDAO.getTypeById(tid);
			gtypes = gtype.getSubTypes(1);
		} catch (Exception e) {
		}
		total = gtypes.size() + 1;
		if (gtype != null) {
			g = new HTMLGenerater(gtype.getSite());
		}
		// System.out.println("system will generate:"+total+" channel");
	}

	protected void work() {
		try {
			Thread.sleep(sleep);
			// System.out.println("system running at:"+counter+"/"+gtypes.size());
			if (counter < gtypes.size()) {
				gtype = gtypes.get(counter);
			} else {
				gtype = typeDAO.getTypeById(tid);
			}
			if(gtype!=null){
				if(gtype.getHtml()==1){
					paras = new ArrayList<Object>();
					paras.add(gtype.getId());
					sql = "k_display='1' and k_ispub='1' and k_type=? order by length(k_order) desc,k_order desc";
					allNews = newsDAO.getNews(sql, paras);
					for (News anews : allNews) {
						g.saveNewsToHtml(anews.getId());
					}
					rows = allNews.size();// 总数
					pageSize = CommUtil.null2Int(gtype.getPagenum());// 每页20条
					totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));// 计算页数
					if (totalPage < 1) {
						totalPage = 1;
					}
					for (int i = 0; i < totalPage; i++) {
						nowPage = i + 1;
						g.saveTypeListToHtml(gtype.getId(), sql, paras, nowPage, rows);
					}
					System.out.println("generate:" + gtype.getName() + ":" + gtype.getHref());
				}
			}
			counter++;
			sum += counter;
		} catch (InterruptedException e) {
			setRunning(false);
		}
	}
}
